package com.zs.grain.ui

import android.app.Application
import androidx.lifecycle.MutableLiveData
import javax.inject.Inject
import com.xnkj1688.semplibrary.mvvm.BaseViewModel
import com.xnkj1688.semplibrary.entity.*
import com.xnkj1688.semplibrary.ulti.BitmapUtil
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.widget.Toast
import com.zs.grain.*
import com.zs.grain.service.*
import io.reactivex.android.schedulers.AndroidSchedulers
import java.io.File
import java.io.FileOutputStream
import java.lang.Exception
import java.util.*
import kotlin.concurrent.schedule
import com.google.gson.JsonObject
import com.jeremyliao.liveeventbus.LiveEventBus
import com.xnkj1688.semplibrary.enums.*
import com.zs.grain.tool.clockManage.LocalDataBase


class ScanQrViewModel @Inject constructor(
    val mApp: Application,
    val mDataService: DataService,
    val mSignalRService: SignalRService,
    val mDeviceService: DeviceService,
    val mSoundService: SoundService
) : BaseViewModel(mApp) {
    //private var mpService: MediaPlayerService = MediaPlayerService()
    val alipay = MutableLiveData<String>()
    val weixin = MutableLiveData<String>()
    val app = MutableLiveData<String>()
    val totalAmount = MutableLiveData<String>()
    val payWay = MutableLiveData<PayWay>()
    val downCount = MutableLiveData<Int>()
    val alipayBtn = MutableLiveData<Drawable>()
    val weixinBtn = MutableLiveData<Drawable>()
    val appBtn = MutableLiveData<Drawable>()
    val backgroundColor = MutableLiveData<Int>()
    lateinit var order: Order
        private set

    private var mCheckTimer: Timer? = null
    private var loading = "res://${mApp.packageName}/${R.mipmap.loading}"
    private var failture = "res://${mApp.packageName}/${R.mipmap.failture}"
    var mSealIndex = -1
    var mSugarIndex = -1
    init {
        val payWays = "," + mDataService.payWays.toLowerCase() + ","
        if (payWays.contains(",alipay,")) alipay.value = ""
        if (payWays.contains(",weixin,")) weixin.value = ""
        if (payWays.contains(",app,")) app.value = ""
    }

    fun init(orderId: Long,goodId:Long,sealIndex:Int,sugarIndex:Int): Boolean {
        mSealIndex = sealIndex
        mSugarIndex = sugarIndex
        var good = mDataService.getGood(goodId ?: 0)
        if (good != null) {
            var array = good.remark?.split(";")
            var color = if (array != null && array.size >= 2) array[1] else "#FFFFFF"
            backgroundColor.value = Color.parseColor(color)
        }

        payWay.value = PayWay.WECHAT
        if (alipay.value != null) alipay.value = loading
        if (weixin.value != null) weixin.value = loading
        if (app.value != null) app.value = loading
        alipayBtn.value = mApp.getDrawable(R.mipmap.alipay2)
        weixinBtn.value = mApp.getDrawable(R.mipmap.weixin1)
        appBtn.value = mApp.getDrawable(R.mipmap.app2)

        this.downCount.value = 120

        var order = mDataService.getOrder(orderId)
        if (order == null) return false
        this.order = order
        this.totalAmount.value = (order.totalAmount / 100f).toString()
        //2019.11.18 添加免费产品判断
        if (order.totalAmount <= 0) {
            mDataService.save(order)
            finishPay(order.id,4)
            //uiNotify.postValue(getNotify("Payed"))
        } else {
            mSignalRService.getPaymentQr(this.order)
                .subscribe({
                    showPaymentQr(it)
                    super.uiNotify.postValue(this.getNotify("Completed"))
                    this.startCheckPaymentTimer()
                }, {
                    postToast("获取二维码失败", Toast.LENGTH_LONG)
                    postUiNofity("Failture")
                })
        }
        return true
    }

    fun onClickAlipay() {
        payWay.value = PayWay.ALIPAY
        alipayBtn.value = mApp.getDrawable(R.mipmap.alipay1)
        weixinBtn.value = mApp.getDrawable(R.mipmap.weixin2)
        appBtn.value = mApp.getDrawable(R.mipmap.app2)
    }

    fun onClickWeixin() {
        payWay.value = PayWay.WECHAT
        alipayBtn.value = mApp.getDrawable(R.mipmap.alipay2)//small
        weixinBtn.value = mApp.getDrawable(R.mipmap.weixin1)
        appBtn.value = mApp.getDrawable(R.mipmap.app2)
    }

    fun onClickApp() {
        payWay.value = PayWay.APP
        alipayBtn.value = mApp.getDrawable(R.mipmap.alipay2)//small
        weixinBtn.value = mApp.getDrawable(R.mipmap.weixin2)
        appBtn.value = mApp.getDrawable(R.mipmap.app1)
    }

    fun onClickConfirm() {
//        if (BuildConfig.DEBUG) {
//            this.uiNotify.value = this.getNotify("Payed")
//            return;
//        }
        if ((alipay.value ?: "").startsWith("res:")
            && (weixin.value ?: "").startsWith("res:")
        ) {
            showToast("支付未完成", Toast.LENGTH_LONG)
            return
        }
        mSignalRService.checkPayment(this.order.id)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it > 0) {
                    order.payWay = it
                    mDataService.save(order)
                    finishPay(order.id,4)
                    //this.uiNotify.postValue(this.getNotify("Payed"))
                } else showToast("支付确认中,请稍后...", Toast.LENGTH_LONG)
            }, {
                it.printStackTrace();
                showToast("网络异常", Toast.LENGTH_LONG)
            })
    }

    fun onClickCancel2(){
        this.uiNotify.value = this.getNotify("Cancel")
    }

    fun onClickCancel() {
        mDataService.insertLog("Option:点击了取消按钮")
        showToast("请稍候...", Toast.LENGTH_SHORT)
        stopCheckPaymentTimer()
        if ((alipay.value ?: "res:").startsWith("res:")
            && (weixin.value ?: "res:").startsWith("res:")
        ) {//OrderSVM
            mDataService.insertLog("Order:用户取消订单号:"+ mDataService.currentOrder?.id.toString())
            mDataService.currentOrder = null
            this.uiNotify.value = this.getNotify("Cancel")
            return
        }
        mSignalRService.closePayment(this.order.id)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it > 0) {
                    order.payWay = it
                    mDataService.save(order)
                    finishPay(order.id,4)
                    //this.uiNotify.postValue(this.getNotify("Payed"))
                } else if (it < 0) {//OrderSVM2
                    mDataService.insertLog("支付取消检查,服务端未下发单号,机器已生成单号:"+ mDataService.currentOrder?.id.toString())
                    mDataService.currentOrder = null
                    this.uiNotify.value = this.getNotify("Cancel")
                }
            }, {
                it.printStackTrace();
                showToast("网络异常", Toast.LENGTH_LONG)
            })
    }

    private var times = 0
    fun startCheckPaymentTimer() {
        times = 0
        this.downCount.postValue(120)
        this.mCheckTimer = Timer()
        this.mCheckTimer?.schedule(1000, 1000, {
            var count = Math.max(0, (downCount.value ?: 1) - 1)
            downCount.postValue(count)
            if (count <= 0) stopCheckPaymentTimer()
            if (count % 30 != 1) return@schedule
            times++
            mSignalRService.checkPayment(order.id)
                .subscribe({
                    if (it > 0) {
                        order.payWay = it
                        mDataService.save(order)
                        //mDataService.insertLog("product:支付成功"+order.toString())//TODO:new log
                        finishPay(order.id,4)
                        //uiNotify.postValue(getNotify("Payed"))
                    } else if (it < 0 && times >= 4) {
                        mDataService.insertLog("Order:超时退出")
                        //mDataService.insertLog("order.id:"+order.id+",currentOrder:" + mDataService.currentOrder?.id.toString())
                        if(order.id == mDataService.currentOrder?.id){
                            mDataService.currentOrder = null
                        }
                        //mDeviceService.isMakingProduct = false
                        uiNotify.postValue(getNotify("Timeout"))
                    }
                }, {
                    it.printStackTrace();
                })
        })
    }

    fun stopCheckPaymentTimer() {
        this.mCheckTimer?.cancel()
        this.mCheckTimer = null
    }

    fun checkPayment(orderId: Long, payWay: Int) {
        mSignalRService.checkPayment2(order.id, payWay)
            .subscribe({
                if (it > 0) {
                    order.payWay = it
                    mDataService.save(order)
                    finishPay(orderId,payWay)
                    //uiNotify.postValue(getNotify("Payed"))
                }
            }, {
                it.printStackTrace();
            })
    }

    private fun showPaymentQr(json: JsonObject) {
        var totalAmount = (json.get("totalAmount")?.asInt ?: 0) / 100f
        this.totalAmount.postValue(totalAmount.toString())

        var path = File("${mDataService.imagesPath}/Payment")
        path.deleteRecursively()
        if (!path.exists()) path.mkdir()

        var qrString = json.get("alipay")?.asString
        if (qrString != null) alipay.postValue(getQrUri(path, "alipay", qrString))
        qrString = json.get("weixin")?.asString
        if (qrString != null) weixin.postValue(getQrUri(path, "weixin", qrString))
        qrString = json.get("app")?.asString
        if (qrString != null) app.postValue(getQrUri(path, "app", qrString))
    }

//    fun stopMPlayer() {
//        if (mpService != null) {
//            mpService?.release()
//        }
//    }
//
//    fun playMusic2(index:Int){
//        mpService?.playMusic2(index)
//    }

    private fun getQrUri(path: File, name: String, qrString: String): String {
        try {
            val bitmap = BitmapUtil.createQRCode(qrString, 400)
            var pathname = "${path.absolutePath}/${name}_${System.currentTimeMillis()}.png"
            var file = File(pathname)
            val fos = FileOutputStream(file)
            try {
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
            } finally {
                fos.close()
            }
            file.deleteOnExit()
            return "file://${pathname}"
        } catch (e: Exception) {
            e.printStackTrace()
            return "";
        }
    }
    //payWay仅用于判断是否APP支付,不做微信或支付宝判断
    private fun finishPay(orderId: Long,payWay:Int){
        if (mDataService.currentOrder?.id==orderId) {
            var seal = if(mSealIndex==2) "有盖" else "无盖"
            var sugar = ""
            when(mSugarIndex){
                1-> sugar = "少少糖"
                3-> sugar = "正常糖"
                else -> sugar = "少糖"
            }
            mDataService.insertLog("Order:产品订单信息:"+seal+","+sugar+","+mDataService.currentOrder?.id.toString())
//            mDeviceService.isMakingProduct = true
            LiveEventBus.get("SyncService.AddMakingProduct").post("")
            this.uiNotify.postValue(this.getNotify("Payed"))
        }else {
            if(payWay != 10)
                this.uiNotify.value = this.getNotify("Cancel")
        }
    }

}